<?php

namespace apiend\modules\course\controllers;

use Yii;
use apiend\components\Controller;
use apiend\modules\course\models\GroupRenameForm;
use common\models\course\CourseGroupUsers;

/**
 * 群聊相关接口
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class GroupController extends Controller {

    public $modelClass = 'apiend\modules\course\models\GroupUserSearch';

    /**
     * @inheritdoc
     */
    protected function rules() {
        return [
            [
                'allow' => true,
                'roles' => ['@'],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    protected function verbs() {
        return [
            'user' => ['GET'],
            'rename' => ['POST'],
            'quit' => ['POST'],
        ];
    }

    /**
     * 获取群成员列表
     * @inheritdoc
     */
    public function actionUser($id) {
        /* @var $modelClass \apiend\modules\course\models\GroupUserSearch */
        $modelClass = new $this->modelClass;
        return $modelClass->search($id);
    }

    /**
     * 修改群名
     * @inheritdoc
     */
    public function actionRename() {
        $model = new GroupRenameForm();
        if (!$model->load(Yii::$app->request->post(), '')) {
            return $model->dumpError('参数校验失败，请检查参数的有效性');
        }
        $model->user_id = $this->token->user_id;
        return $model->save();
    }

    /**
     * 退出群聊
     * @inheritdoc
     */
    public function actionQuit() {
        $group_id = Yii::$app->request->post('group_id');
        $userid = $this->token->user_id;

        $guser = CourseGroupUsers::findOne([
            'group_id' => $group_id,
            'user_id' => $userid,
        ]);
        if ($guser->group && $guser->group->user_id == $userid) {
            return false;
        }
        if ($guser->delete()) {
            $quit = Yii::$app->rongyun->transport('group')->quit($userid, $group_id);
            if ($quit !== false) {
                return true;
            }
        }
        return false;
    }

}
